//
//  BN_DynamicViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-3-28.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//
#import "BN_DynamicViewController.h"
#import "BN_UserHelper.h"
#import "BN_UseAgreementView.h"
#import "iMB_DownloadNetVideo.h"

@interface BN_DynamicViewController () {
    //数据资料
    BN_DynamicClassData *dynamicData;
    BN_DynamicParentData *parentData;
    IMB_SaveCameraInfo *saveCameraInfo;
    iMB_DownloadNetVideo *downloadNetVideo;
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
}

@end

@implementation BN_DynamicViewController

- (void)dealloc
{
    NSLog(@"动态视图控制器释放了...");
}

// 判断当前显示内容为家长或班级
- (void)getIsClassOrParent {
    if (self.isClassOrParent) {
        [[NSUserDefaults standardUserDefaults]setInteger:0 forKey:USERDEFAULTS_CLASSPARENT];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else {
        [[NSUserDefaults standardUserDefaults]setInteger:1 forKey:USERDEFAULTS_CLASSPARENT];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL videoStyle = [userDefaults boolForKey:USERDEFAULTS_VIDEO_STYLE];
    // YES为全屏状态
    if (!videoStyle) {
        // 广播 停止视频播放
        [[NSNotificationCenter defaultCenter]postNotificationName:@"K_ANYTIME_REMOVE_MOVIE" object:nil];
    }
    [self cancelHintView];
}

// 程序第一次弹出使用协议控制器
- (void)toHintUseAgreement {

    // 弹出UIViewController
    BN_PopAgreementViewController *popAgreementVc = [[BN_PopAgreementViewController alloc]init];
    UINavigationController *navCtrl = [[UINavigationController alloc]initWithRootViewController:popAgreementVc];
    [self.navigationController presentViewController:navCtrl animated:YES completion:NULL];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"POP_AGREEMENTCONTROLLER_ED"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"POP_AGREEMENTCONTROLLER_ED"];
        [self toHintUseAgreement];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:YES forKey:FIRSTRUN];
    [userDefaults setInteger:0 forKey:USERDEFAULTS_DYNAMICORNOTICE];
    [userDefaults setInteger:10 forKey:USERDEFAULTS_KINDERSECTION];
    [userDefaults synchronize];
    
    // UI+64
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    // 显示Tabbar
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    [self getIsClassOrParent];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    
    // 未读消息
    /*UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"xiaoxi"] style:UIBarButtonItemStylePlain target:self action:@selector(xiaoxiAction)];
    self.navigationItem.leftBarButtonItem = leftItem;*/
    
    // 权限样式
    [self navgationBarDispStyle:-1];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(isDisplay:) name:KDISPLAYHIDEDYNAMICUIVIEW object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushPinglunVC:) name:KPUSHCONTROLLER_PINGLUN object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(switchScrollViewContentOffset:) name:KDYNAMIC_SCROLLOFFSET object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedCameraAction:) name:@"K_CAMERA_END" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(classModelRefresh:) name:KCLASSAUTOREFRESH object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(parentModelRefresh:) name:KPARENTAUTOREFRESH object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lookOtherPersonalInfo:) name:K_LOOK_OTHER_PERSONAL_INFO object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openReportVc:) name:K_REPORT_INFO object:nil];
    
    // 添加titile
    self.userInfo = [BN_UserHelper unArchiverAccountInfo];
    NSString *schoName = self.userInfo.schoName;
    NSString *clasName = self.userInfo.clasName;
    
    // 园长没有className
    NSString *title = nil;
    if ([clasName isEqual:[NSNull null]]) {
        title = schoName;
    }else {
        title = [schoName stringByAppendingString:clasName];
    }
    self.title = title;
    self.tabBarItem.title = @"动态";
    
    // 微视效果分割线
    self.lineLabel.frame = CGRectMake(0, FULLSCREEN_HEIGHT/2, SCREEN_WIDTH, 1);

    // 合并视图
    [self combinationView];
    
    // 小球提示
    [self viewLoadHintView];
}

- (void)changeLeftNews {
    UILabel *newsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 24, 24)];
    newsLabel.text = [NSString stringWithFormat:@"%@",self.newsDict[@"postNumb"]];
    newsLabel.backgroundColor = [UIColor redColor];
    newsLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:newsLabel];
}

#pragma mark Action
- (void)openReportVc:(NSNotification *)notification {
    BN_ReportViewController *reportVc = [[BN_ReportViewController alloc]init];
    [self.navigationController pushViewController:reportVc animated:YES];
}

- (void)lookOtherPersonalInfo:(NSNotification *)notification {
    NSArray *receiveArr = notification.object;
    NSInteger userType = [receiveArr[0] integerValue];
    if (userType != ENUM_ROLE_PARENT) {
        // 园长和老师的UI
        // BN_TeacherMeansViewController *teacherLeaderInfoVc = [[BN_TeacherMeansViewController alloc]init];
        // [self.navigationController pushViewController:teacherLeaderInfoVc animated:YES];
    }else {
        // 家长的UI
        // BN_ParentMeansViewController *parentInfoVc = [[BN_ParentMeansViewController alloc]init];
        // [self.navigationController pushViewController:parentInfoVc animated:YES];
    }
} // 查看其他人的个人信息 postUserType && postUserId

- (void)classModelRefresh:(NSNotification *)notification {
    [dynamicData classRefresh];
}
 
- (void)parentModelRefresh:(NSNotification *)notification {
    [parentData parentRefresh];
}

- (void)finishedCameraAction:(NSNotification *)notification {
    BN_CreateContentViewController *createContentVC = [[BN_CreateContentViewController alloc]init];
    saveCameraInfo = [IMB_SaveCameraInfo sharedSaveCameraInfo];
    createContentVC.cameraAffirmDic = saveCameraInfo.cameraDict;
    [createContentVC toHintMessage:^(BOOL isSuccess) {
        if (isSuccess) {
            [LZCHINT title:@"上传成功" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
        }
    }];
    
    [self.navigationController pushViewController:createContentVC animated:NO];

    /*方案:CATransition *transition = [CATransition animation];
    transition.duration = 0.3;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = @"fade";
    // 其他动画效果 @"cube" @"moveIn" @"reveal" @"fade"(default) @"pageCurl" @"pageUnCurl" @"suckEffect" @"rippleEffect" @"oglFlip"
    transition.subtype = kCATransitionFromRight;
    [self.navigationController pushViewController:createContentVC animated:NO];
     [self.navigationController.view.layer addAnimation:transition forKey:nil];*/
}

- (void)takeVCR {
    IMB_CameraViewController *cameraVC = [[IMB_CameraViewController alloc]initWithUIChange:^(NSString *info) {
        self.navigationController.navigationBarHidden = NO;
        self.tabBarController.tabBar.hidden = NO;
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    }];
    [self.navigationController presentViewController:cameraVC animated:NO completion:NULL];
}

- (void)goCreateVC {
    BN_CreateContentViewController *creaContVC_ = [[BN_CreateContentViewController alloc]init];
    [creaContVC_ toHintMessage:^(BOOL isSuccess) {
        if (isSuccess) {
            [LZCHINT title:@"上传成功" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
        }
    }];
    [self.navigationController pushViewController:creaContVC_ animated:YES];
}

/*
- (void)xiaoxiAction {
    BN_DiscListViewController *discListVC = [[BN_DiscListViewController alloc]init];
    discListVC.flg = @"message";
    [self.navigationController pushViewController:discListVC animated:YES];
}*/

#pragma mark 组合 最底层视图 动态按钮 滑动视频 列表
- (void)combinationView {
    
    self.bottomView = nil;
    self.classParentView = nil;
    self.dynamicScrollView = nil;
    self.classTableView = nil;
    self.parentTableView = nil;
    
    if (IOS7) {
        // 初始化最底层视图 扥...
        
        self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT)];
        self.bottomView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:self.bottomView];
        [self.view sendSubviewToBack:self.bottomView];
        
        // 班级动态/家长动态
        _classParentView = [[BN_ClassParentDynamic alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, CLASSPARENTVIEWHEIGHT)];
        [_classParentView dynamicClassParentChange:^(BOOL isChange) {
            if (isChange) {
                [self navgationBarDispStyle:0];
            }else {
                [self navgationBarDispStyle:SCREEN_WIDTH];
            }
        }];
        _classParentView.layer.shadowOffset = CGSizeMake(0, 1);
        _classParentView.layer.shadowColor = [[UIColor grayColor] CGColor];
        _classParentView.layer.shadowOpacity = 0.5;
        _classParentView.layer.shadowRadius = 1;
        _classParentView.backgroundColor = [UIColor whiteColor];
        [_classParentView loadBtnView];
        [self.view addSubview:_classParentView];
        
        //滑动视图
        self.dynamicScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.bottomView.frame.size.height)];
        self.dynamicScrollView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        self.dynamicScrollView.delegate = self;
        [self.dynamicScrollView setContentSize:CGSizeMake(SCREEN_WIDTH*2,self.bottomView.frame.size.height)];
        self.dynamicScrollView.pagingEnabled = YES;
        self.dynamicScrollView.directionalLockEnabled = YES;
        self.dynamicScrollView.showsHorizontalScrollIndicator = NO;
        self.dynamicScrollView.showsVerticalScrollIndicator = NO;
        self.dynamicScrollView.backgroundColor = [UIColor clearColor];
        [self.bottomView addSubview:self.dynamicScrollView];
        // 根据scrollView.contentOffset程序记录当前是班级||家长显示
        if (self.dynamicScrollView.contentOffset.x == 0) {
            self.isClassOrParent = YES;
            [self getIsClassOrParent];
        }else {
            self.isClassOrParent = NO;
            [self getIsClassOrParent];
        }
        
        //班级动态列表
        self.classTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.bottomView.frame.size.height)];
        self.classTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        self.classTableView.contentInset = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);
        self.classTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);

        __weak typeof(self) weakSelf = self;
        if (!dynamicData) {
            dynamicData = [[BN_DynamicClassData alloc]init];
        }
        [dynamicData toDynamic_NoticeReloadList:^(BOOL isReload,BOOL isScrollToTop) {
            if (isReload) {
                [weakSelf cancelHintView];
            }
        }];
        dynamicData.lineLabel = self.lineLabel;
        self.classTableView = dynamicData.classTableView;
        [self.classTableView scrollsToTop];
        [self.dynamicScrollView addSubview:self.classTableView];
        
        // 家长动态列表
        self.parentTableView = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, self.bottomView.frame.size.height)];
        self.parentTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        self.parentTableView.contentInset = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);
        self.parentTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);
        if (!parentData) {
            parentData = [[BN_DynamicParentData alloc]init];
        }
        [parentData toDynamic_NoticeReloadList:^(BOOL isReload,BOOL isScrollToTop) {
            if (isReload && isScrollToTop) {
                [weakSelf.parentTableView reloadData];
                [weakSelf.parentTableView
                 setContentOffset:CGPointMake(weakSelf.parentTableView.contentOffset.x, -(64+CLASSPARENTVIEWHEIGHT)) animated:YES];
            }else {
                [weakSelf.parentTableView reloadData];
            }
        }];
        [parentData tableViewRowForCellReload:^(NSArray *indexArr,BOOL isAll) {
            if (isAll) {
                [weakSelf.parentTableView reloadData];
            }else {
                [weakSelf.parentTableView reloadRowsAtIndexPaths:indexArr withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
        if ([self.parentTableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [self.parentTableView setSeparatorInset:UIEdgeInsetsZero];
        }
        // 下拉刷新
        MJRefreshHeaderView *header = [MJRefreshHeaderView header];
        header.scrollView = self.parentTableView;
        header.delegate = parentData;
        _header = header;
        
        // 上拉加载更多
        MJRefreshFooterView *footer = [MJRefreshFooterView footer];
        footer.scrollView = self.parentTableView;
        footer.delegate = parentData;
        _footer = footer;
        
        [self setExtraCellLineHidden:self.parentTableView];
        self.parentTableView.delegate = parentData;
        self.parentTableView.dataSource = parentData;
        [self.dynamicScrollView addSubview:self.parentTableView];
        
    }else {
        
        // 初始化最底层视图...
        self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.bottomView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.bottomView];
        
        // 班级动态/家长动态
        _classParentView = [[BN_ClassParentDynamic alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CLASSPARENTVIEWHEIGHT)];
        _classParentView.backgroundColor = [UIColor whiteColor];
        [_classParentView dynamicClassParentChange:^(BOOL isChange) {
            if (isChange) {
                [self navgationBarDispStyle:0];
            }else {
                [self navgationBarDispStyle:SCREEN_WIDTH];
            }
        }];
        _classParentView.layer.shadowOffset = CGSizeMake(0, 1);
        _classParentView.layer.shadowColor = [[UIColor grayColor] CGColor];
        _classParentView.layer.shadowOpacity = 0.5;
        _classParentView.layer.shadowRadius = 1;
        [_classParentView loadBtnView];
        [self.view addSubview:_classParentView];
        
        // 滑动视图
        self.dynamicScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.dynamicScrollView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        self.dynamicScrollView.delegate = self;
        [self.dynamicScrollView setContentSize:CGSizeMake(SCREEN_WIDTH*2,SCREEN_HEIGHT)];
        self.dynamicScrollView.scrollsToTop = NO;
        self.dynamicScrollView.pagingEnabled = YES;
        self.dynamicScrollView.directionalLockEnabled = YES;
        self.dynamicScrollView.showsHorizontalScrollIndicator = NO;
        self.dynamicScrollView.showsVerticalScrollIndicator = NO;
        [self.bottomView addSubview:self.dynamicScrollView];
        // 根据scrollView.contentOffset程序记录当前是班级||家长显示
        if (self.dynamicScrollView.contentOffset.x == 0) {
            self.isClassOrParent = YES;
            [self getIsClassOrParent];
        }else {
            self.isClassOrParent = NO;
            [self getIsClassOrParent];
        }
        
        // 班级动态列表
        self.classTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.classTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        if (!dynamicData) {
            dynamicData = [[BN_DynamicClassData alloc]init];
        }
        __weak typeof(self) weakSelf = self;
        [dynamicData toDynamic_NoticeReloadList:^(BOOL isReload,BOOL isScrollToTop) {
            if (isReload) {
                [weakSelf cancelHintView];
            }
        }];
        dynamicData.lineLabel = self.lineLabel;
         self.classTableView = dynamicData.classTableView;
        [self.dynamicScrollView addSubview:self.classTableView];
        
        // 家长动态列表
        self.parentTableView = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.parentTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        self.parentTableView.tag = 2;
        
        if (!parentData) {
            parentData = [[BN_DynamicParentData alloc]init];
        }
        [parentData toDynamic_NoticeReloadList:^(BOOL isReload,BOOL isScrollToTop) {
            if (isReload && isScrollToTop) {
                [weakSelf.parentTableView reloadData];
                [weakSelf.parentTableView
                 setContentOffset:CGPointMake(weakSelf.parentTableView.contentOffset.x, -(64+CLASSPARENTVIEWHEIGHT)) animated:YES];
            }else {
                [weakSelf.parentTableView reloadData];
            }
        }];
        [parentData tableViewRowForCellReload:^(NSArray *indexArr,BOOL isAll) {
            if (isAll) {
                [self.parentTableView reloadData];
            }else {
                [self.parentTableView reloadRowsAtIndexPaths:indexArr withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
        
        [self setExtraCellLineHidden:self.parentTableView];
        self.parentTableView.frame = CGRectMake(320, 0, SCREEN_WIDTH, SCREEN_HEIGHT-CLASSPARENTVIEWHEIGHT);
        self.parentTableView.contentInset = UIEdgeInsetsMake(CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR+10, 0);
        self.parentTableView.scrollIndicatorInsets = UIEdgeInsetsMake(CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR+10, 0);
        // 下拉刷新
        MJRefreshHeaderView *header = [MJRefreshHeaderView header];
        header.scrollView = self.parentTableView;
        header.delegate = parentData;
        _header = header;
        
        // 上拉加载更多
        MJRefreshFooterView *footer = [MJRefreshFooterView footer];
        footer.scrollView = self.parentTableView;
        footer.delegate = parentData;
        _footer = footer;
        self.parentTableView.delegate = parentData;
        self.parentTableView.dataSource = parentData;
        [self.dynamicScrollView addSubview:self.parentTableView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    float index = scrollView.contentOffset.x;
    NSLog(@"%f",index);
    if (index == 320) {
        // UI
        [self navgationBarDispStyle:index];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setInteger:1 forKey:USERDEFAULTS_CLASSPARENT];
        [userDefaults setObject:@"parent" forKey:USERDEFAULTS_SWITCHDYNAMIC];
        [userDefaults synchronize];
        // 通知改变班级/家长的状态
        [[NSNotificationCenter defaultCenter]postNotificationName:KSWITCHCLASSPARENT object:nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"K_ANYTIME_REMOVE_MOVIE" object:nil];
        self.isClassOrParent = NO;
    }
    if (index == 0) {
        // UI
        [self navgationBarDispStyle:index];

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setInteger:0 forKey:USERDEFAULTS_CLASSPARENT];
        [userDefaults setObject:@"class" forKey:USERDEFAULTS_SWITCHDYNAMIC];
        [userDefaults synchronize];
        [[NSNotificationCenter defaultCenter]postNotificationName:KSWITCHCLASSPARENT object:nil];
        
        self.isClassOrParent = YES;
    }
}

#pragma mark 显示隐藏
- (void)isDisplay:(NSNotification *)notification {
    NSString *state = notification.object;
    if ([state isEqualToString:@"display"]) {
        self.classParentView.hidden = NO;
    }else {
        self.classParentView.hidden = YES;
    }
}

// 通知群 方法
- (void)pushPinglunVC:(NSNotification *)notification {
    BN_PingLunViewController *pinglunVC= [[BN_PingLunViewController alloc]initWithNibName:@"BN_PingLunViewController" bundle:nil];
    pinglunVC.postId = notification.object;
    [self.navigationController pushViewController:pinglunVC animated:YES];
}

#pragma mark 
#pragma mark scrollView进行切换
- (void)switchScrollViewContentOffset:(NSNotification *)notification {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *state = [userDefaults objectForKey:USERDEFAULTS_SWITCHDYNAMIC];
    if ([state isEqualToString:@"class"]) {
        self.isClassOrParent = YES;
        CGPoint position = CGPointMake(0, 0);
        [self.dynamicScrollView setContentOffset:position animated:YES];
    }else {
        self.isClassOrParent = NO;
        CGPoint position = CGPointMake(320, 0);
        [self.dynamicScrollView setContentOffset:position animated:YES];
    }
}

@end
